#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        vector<vector<int>> f(n, vector<int>(3, -prices[0]));
        vector<vector<int>> g(n, vector<int>(3));
        for (int i = 1; i < n; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                f[i][j] = max(f[i - 1][j], g[i - 1][j] - prices[i]);
                if (j - 1 < 0)
                {
                    g[i][j] = g[i - 1][j];
                }
                else
                {
                    g[i][j] = max(g[i - 1][j], f[i - 1][j - 1] + prices[i]);
                }
            }
        }
        int max = g[n - 1][0];
        for (int i = 1; i < 3; i++)
        {
            if (g[n - 1][i] > max)
            {
                max = g[n - 1][i];
            }
        }
        return max;
    }
};